package com.yunkaweilai.android.activity.member;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.web.WebActivity;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.Web;
import com.yunkaweilai.android.model.home.RecordListBean;
import com.yunkaweilai.android.model.member.MemberHeadModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

/**
 * 消费记录
 * Created by Administrator on 2017/6/28.
 */

public class RechargeRecordActivity extends BaseActivity implements BGARefreshLayout.BGARefreshLayoutDelegate {
    public static final String ConsumeMEMBER_MODEL = "ConsumeMEMBER_MODEL";
    public static final String ConsumeMEMBER_BUNDLE = "ConsumeMEMBER_BUNDLE";

    @BindView(R.id.id_listview)
    ListView idListview;
    @BindView(R.id.id_tv_all_member)
    TextView idTvAllMember;
    @BindView(R.id.content_view)
    BGARefreshLayout contentView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    @BindView(R.id.id_img_head)
    ImageView idImgHead;
    @BindView(R.id.id_tv_name)
    TextView idTvName;
    @BindView(R.id.id_tvcard_number)
    TextView idTvcardNumber;
    @BindView(R.id.id_tv_card_infor)
    TextView idTvCardInfor;

    private ArrayList<RecordListBean.data.list> list = new ArrayList<>();
    private CommonAdapter<RecordListBean.data.list> adapter;
    private MemberHeadModel model;
    private int mpage = 1;
    private boolean mHasMore = true;

    public static void actionStart(Context context, MemberHeadModel model) {
        Intent intent = new Intent(context, RechargeRecordActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(ConsumeMEMBER_MODEL, model);
        intent.putExtra(ConsumeMEMBER_BUNDLE, bundle);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge_record);
        ButterKnife.bind(this);
        initRefreshLayout(contentView, this, true);
        idMultipleStatusView.showLoading();
        model = (MemberHeadModel) getIntent().getBundleExtra(ConsumeMEMBER_BUNDLE).getSerializable(ConsumeMEMBER_MODEL);
        initHeadView();
        initAdapter();
        initHttp(true);
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                idMultipleStatusView.showLoading();
                initHttp(true);
            }
        });
        initClick();
    }

    private void initClick() {
        idListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RecordListBean.data.list listBean = list.get(position);
                WebActivity.actionStart(mAc, Web.ORDER_INFO + "?tid=" + listBean.getTid() +
                        "&token=" + BaseApplication.getToken());
            }
        });
        idImgHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.ImageEnlage(mAc, "1", model.getMember_avatar(), model.getMember_sex());
            }
        });
    }

    private void initHeadView() {
        new TitleBuilder(mAc).setTitleText("充值记录").setLeftImage(R.mipmap.ic_go_back)
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
        Utils.MemberHeadImg(mAc, model.getMember_avatar(), model.getMember_sex(), idImgHead);
        idTvName.setText(model.getMember_name() + " (" + model.getLevel_name() + ": " + model.getCard_no() + ")");
        idTvCardInfor.setText("折扣：" + model.getDiscount() / 10 + "折   积分：" + model.getMember_points() + "   余额：" + model.getMember_price());
    }

    private boolean initHttp(final boolean refresh) {
        mpage = refresh ? 1 : mpage;
        if ((!mHasMore) && (!refresh)) {
            contentView.endLoadingMore();
            showToast("没有更多数据了");
            return false;
        }
        HttpRequest.postUrl(Api.APP_RECORD_LIST)
                .addParams("type_id", "17")
                .addParams("ShowPage", "1")
                .addParams("PageSize", "10")
                .addParams("CurrPage", "" + mpage)
                .addParams("days", "0")
                .addParams("member_id", model.getId())
                .log(TAG)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        endRefreshOrLoad(refresh);
                        Gson gson = new Gson();
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            mpage++;
                            RecordListBean consumeModel = gson.fromJson(json, RecordListBean.class);
                            if (refresh) {
                                list.clear();
                            }
                            if (consumeModel.getData().getList() != null && consumeModel.getData().getList().size() != 0) {
                                list.addAll(consumeModel.getData().getList());
                                adapter.notifyDataSetChanged();
                                mHasMore = consumeModel.getData().getPage().isNext();//是否还有下一页
                                idTvAllMember.setText("共" + consumeModel.getData().getPage().getCount() + "次");
                                if (idMultipleStatusView != null) {
                                    idMultipleStatusView.showContent();
                                }
                            } else {
                                mHasMore = false;
                                if (refresh) {
                                    if (idMultipleStatusView != null) {
                                        idTvAllMember.setText("共0次");
                                        idMultipleStatusView.showEmpty();
                                    }
                                }
                            }
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });

        return true;
    }


    /**
     * 结束刷新组件
     *
     * @param refresh
     */
    private void endRefreshOrLoad(boolean refresh) {
        if (refresh) {
            if (contentView != null) {
                contentView.endRefreshing();
            }
        } else {
            if (contentView != null) {
                contentView.endLoadingMore();
            }
        }
    }

    private void initAdapter() {
        adapter = new CommonAdapter<RecordListBean.data.list>(mAc, R.layout.item_list_order_home_for_charge, list) {
            @Override
            protected void convert(ViewHolder viewHolder, RecordListBean.data.list item, int position) {
                viewHolder.setText(R.id.line1_right, item.getTid());
                viewHolder.setText(R.id.line2_right, item.getConsume_time());
                viewHolder.setText(R.id.line3_right, item.getStrrecharge_type());
                viewHolder.setVisible(R.id.item_list_order_home_line6, false);
                viewHolder.setVisible(R.id.line1_right_refund, false);
                if (item.isRefund()) {
                    viewHolder.setVisible(R.id.line1_right_refund, true);
                }
                if (item.getStrrecharge_type() != null) {
                    if (item.getStrrecharge_type().equals("储值充值") || item.getStrrecharge_type().equals("微信自助充值")) {
                        viewHolder.setText(R.id.line4_left, "实充/赠送");
                    } else if (item.getStrrecharge_type().equals("微信自助计次充值")) {
                        viewHolder.setText(R.id.line4_left, "实收");
                    } else {
                        viewHolder.setText(R.id.line4_left, "应收/实收");
                    }
                } else {
                    viewHolder.setText(R.id.line4_left, "应收/实收");
                }
                if (item.getStrrecharge_type() != null && item.getPayment_type() != null && (item.getStrrecharge_type().equals("储值充值") || item.getStrrecharge_type().equals("微信自助充值"))) {
                    float x1 = Float.parseFloat(item.getZ_goods_price()) - Float.parseFloat(item.getS_payment());
                    viewHolder.setText(R.id.line4_right, item.getZ_discount_price() + "/" + x1 + "(" + item.getPayment_type() + ")");
                } else if (item.getStrrecharge_type() != null && item.getPayment_type() != null && item.getStrrecharge_type().equals("微信自助计次充值")) {
                    viewHolder.setText(R.id.line4_right, item.getS_payment() + "(" + item.getPayment_type() + ")");
                } else {
                    viewHolder.setText(R.id.line4_right, item.getZ_discount_price() + "/" + item.getS_payment() + "(" + item.getPayment_type() + ")");
                }
                if (item.getStrGoodsList() != null && item.getStrGoodsList().equals("无商品")) {
                    viewHolder.setVisible(R.id.item_list_order_home_line6, false);
                    viewHolder.setVisible(R.id.order_view_bottom, false);
                } else {
                    viewHolder.setVisible(R.id.order_view_bottom, true);
                    viewHolder.setVisible(R.id.item_list_order_home_line6, true);
                    viewHolder.setText(R.id.line6_left, item.getStrGoodsList());
                }
            }

        };
        idListview.setAdapter(adapter);
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        initHttp(true);
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return initHttp(false);
    }
}
